package com.baoyouqun.base.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.baoyouqun.service.UserRoleService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 拦截非超管的删除接口请求
 */
@Component
@Slf4j
public class DeleteOperationInterceptor implements HandlerInterceptor {

    // 超管角色标识（根据实际项目定义调整，如角色ID或角色编码）
    private static final String SUPER_ADMIN_ROLE_CODE = "R010000";
    @Resource
    private UserRoleService userRoleService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 判断是否为删除操作（DELETE方法或路径包含delete关键词）
        if (isDeleteOperation(request)) {
            log.info("拦截到删除操作请求，路径：{}，方法：{}", request.getRequestURI(), request.getMethod());

            // 2. 检查用户是否登录
            if (!StpUtil.isLogin()) {
                returnJson(response, "{\"code\":401,\"msg\":\"未登录，无法执行删除操作\"}");
                return false;
            }

            // 3. 获取当前登录用户ID
            String userId = StpUtil.getLoginIdAsString();

            // 4. 检查用户是否为超管角色
            String isSuperAdmin = userRoleService.getRoleIdByUserId(userId);
            if (!SUPER_ADMIN_ROLE_CODE.equals(isSuperAdmin)) {
                log.warn("非超管用户[{}]尝试执行删除操作，已拦截", userId);
                returnJson(response, "{\"code\":403,\"msg\":\"权限不足，仅超管可执行删除操作\"}");
                return false;
            }
        }

        // 非删除操作或超管用户，放行
        return true;
    }

    /**
     * 判断是否为删除操作
     * 规则：HTTP方法为DELETE 或 路径包含"/delete"（可根据实际接口规范调整）
     */
    private boolean isDeleteOperation(HttpServletRequest request) {
        String method = request.getMethod();
        String requestUri = request.getRequestURI();

        // 匹配DELETE方法 或 路径包含/delete（不区分大小写）
        return "DELETE".equals(method)
                || requestUri.toLowerCase().contains("/delete");
    }

    /**
     * 向客户端返回JSON响应
     */
    private void returnJson(HttpServletResponse response, String json) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(json);
        writer.flush();
        writer.close();
    }
}